﻿// <copyright file="VerificationController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.Maintenance
{
    using MesAPI.Extensions.AuthContext;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using PublicData;
    using PublicModelsAndEntities.Entities.Function;
    using PublicModelsAndEntities.Models.MainsortRecord;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.Function;
    using XinjeMesProgram.Entities.Maintenance;

    /// <summary>
    /// 核对界面控制器.
    /// </summary>
    [ApiController]
    [Authorize]
    public class VerificationController : ControllerBase
    {
#pragma warning disable SA1000 // Keywords should be spaced correctly
#pragma warning disable CS8602 // 解引用可能出现空引用。
        private ResponseModel response = new();

        /// <summary>
        /// 核对页面获取基础数据信息.
        /// </summary>
        /// <param name="pageSize">每页记录条数 .</param>
        /// <param name="currentPage">当前页码 .</param>
        /// /// <param name="delivery_numberIn">快递单号 .</param>
        /// <param name="oneDimensionalCode">产品序列号（一维码）.</param>
        /// <param name="name">客户名称 .</param>
        /// <param name="unknown">不明 .</param>
        /// <param name="warehousingDate">时间 .</param>
        /// <param name="productCategory">产品组类别 .</param>
        /// <returns>.</returns>
        [Route("/api/v1/verifySearchE/verifySearch")]
        [HttpGet]
        public ResponseModel GetVerificationInfo(int pageSize, int currentPage, string? delivery_numberIn, string? oneDimensionalCode, string? name, string? unknown, string? warehousingDate, string? productCategory)
        {
            using (FactoryMesContext context = new())
            {// 最高管理员 //主管  //一级用户
                var info = from sr in context.MainsortRecord
                           where sr.State == "2"
                           select new MainsortModel
                           {
                               ID = sr.ID,
                               State = sr.State,
                               WarehousingDate = sr.WarehousingDate,
                               delivery_nameIn = sr.Delivery_NameIn,
                               delivery_numberIn = sr.Delivery_NumberIn,
                               Name = sr.Name,
                               Consignee = sr.Consignee,
                               contact_information = sr.Contact_Information,
                               receiving_contact = sr.Receiving_Contact,
                               shipping_address = sr.Shipping_Address,
                               one_dimensional_code = sr.One_Dimensional_Code,
                               product_model = sr.Product_Model,
                               product_classification = sr.Product_Classification,
                               Product_Name = sr.Product_Name,
                               productCategory = sr.Product_Category,
                               Guarantee = sr.Guarantee,
                               purchasing_unit = sr.Purchasing_Unit,
                               Salesman = sr.Salesman,
                               delivery_time = sr.Delivery_Time,
                               first_iaddress = sr.First_Address,
                               SortingUserId = sr.SortingUserId,
                               FinalConfirmUserId = sr.FinalConfirmUserId,
                               SortingUserName = XinjeCloudUserQuery.GetUserName(sr.SortingUserId),
                               FinalConfirmUserName = XinjeCloudUserQuery.GetUserName(sr.FinalConfirmUserId),
                               UpdateUserName = XinjeCloudUserQuery.GetUserName(sr.UpdateUserId),
                               SortingDate = sr.SortingDate,
                               assignPersonnel = XinjeCloudUserQuery.GetUserName(sr.AssignPersonnelUserId),
                               AllocationState = sr.AllocationState,
                               customerLevel = sr.CustomerLevel,
                           };

                if (!string.IsNullOrEmpty(warehousingDate))
                {
                    info = info.Where(x => x.WarehousingDate.Contains(warehousingDate));
                }

                if (!string.IsNullOrEmpty(oneDimensionalCode))
                {
                    info = info.Where(x => x.one_dimensional_code.Contains(oneDimensionalCode));
                }

                if (!string.IsNullOrEmpty(name))
                {
                    info = info.Where(x => x.Name.Contains(name));
                }

                if (!string.IsNullOrEmpty(delivery_numberIn))
                {
                    info = info.Where(x => x.delivery_numberIn.Contains(delivery_numberIn));
                }

                if (!string.IsNullOrEmpty(productCategory))
                {
                    if (productCategory != "所有")
                    {
                        info = info.Where(x => x.productCategory.Contains(productCategory));
                    }
                }

                if (!string.IsNullOrEmpty(unknown))
                {
                    if (unknown != "所有")
                    {
                        if (unknown == "不明")
                        {
                            info = info.Where(x => x.contact_information == "不明");
                        }
                        else
                        {
                            info = info.Where(x => x.contact_information != "不明");
                        }
                    }
                }

                int count = 0;

                count = info.ToList().Count;
                this.response.SetData(info.OrderByDescending(x => x.SortingDate).ToList().ListPaged(currentPage, pageSize), count);
            }

            return this.response;
        }

        /// <summary>
        /// 审核状态提交.
        /// </summary>
        /// <param name="id">唯一标识 .</param>
        /// <returns>.</returns>
        [Route("/api/v1/verifyhandoverE/verifyhandover")]
        [HttpPost]
        public ResponseModel ConfirmInfo(string id)
        {
            using (FactoryMesContext context = new())
            {
                var sr = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
                if (sr != null)
                {
                    sr.State = "3";
                    sr.AllocationState = "0";
                    sr.CheckUserId = AuthContextService.CurrentUser.UserID;
                    sr.CheckDateTime = DateTime.Now;
                    var query = MyDataAutoMapper.Mapper.Map<MainsortRecordModel, RepairProductModel>(sr);
                    query.State = "0";
                    context.RepairProduct.Add(query);
                    var cost = MyDataAutoMapper.Mapper.Map<MainsortRecordModel, MaintenanceCostModel>(sr);
                    context.MaintenanceCost.Add(cost);
                    context.SaveChanges();
                }
                else
                {
                    this.response.SetError("没找到该分拣单");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 打回：若小组长核对数据有问题，则打回该条数据到分拣 .
        /// </summary>
        /// <param name="id">id .</param>
        /// <param name="state">状态（共7个，可能增加一个包装）.</param>
        /// <returns>.</returns>
        [Route("/api/v1/verifyReturnedE/verifyReturned")]
        [HttpPost]
        public ResponseModel Returned(string id, string state)
        {
            using var context = new FactoryMesContext();
            var vre = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
            var rp = context.RepairProduct.FirstOrDefault(x => x.ProductId == id);
            var d = context.Deliver.FirstOrDefault(x => x.ProductId == id);
            if (vre != null)
            {
                FactoryMesContext factoryMes = new();

                // 待核对
                if (state == "2")
                {
                    vre.State = "1"; // 已收货
                }

                // 待维修
                if (state == "3")
                {
                    if (AuthContextService.CurrentUser.UserType == XinjeMesProgram.Entities.User.UserType.PrimaryUser
                        || AuthContextService.CurrentUser.UserType == XinjeMesProgram.Entities.User.UserType.SuperAdministator
                        || AuthContextService.CurrentUser.UserType == XinjeMesProgram.Entities.User.UserType.GeneralUser)
                    {
                        vre.State = "2"; // 待核对
                        if (vre != null)
                        {
                            string sQL = string.Format("DELETE FROM RepairProduct WHERE ProductId = '{0}';select a.ProductId  from RepairProduct a  where a.ProductId='{0}'", id);  // 先删除，再查找  // 维修表
                            _ = factoryMes.Deletedata.FromSqlRaw(sQL).ToList();  // 执行SQL

                            string sQLa = string.Format("DELETE FROM MaintenanceCost WHERE ID = '{0}';select a.ID  from MaintenanceCost a  where a.ID='{0}'", id);  // 先删除，再查找 // 费用表
                            _ = factoryMes.Deletedata.FromSqlRaw(sQLa).ToList();  // 执行SQL
                        }
                        else
                        {
                            this.response.SetError("没找到此数据");
                        }
                    }
                    else
                    {
                        this.response.SetError("该用户权限不足！");
                    }
                }
                else if (state == "5" && rp.MaintenanceEntryTime != null)
                {
                    rp.MaintenanceEntryTime = null; // 维修中，收费
                }

                // 维修中
                else if (state == "5" && rp.MaintenanceEntryTime == null)
                {
                    vre.State = "3"; // 待维修
                }

                // 维修完成
                else if (state == "6")
                {
                    string sQLa1 = string.Format("DELETE FROM Deliver WHERE ProductId = '{0}';select a.ProductId  from Deliver a  where a.ProductId='{0}'", id);  // 先删除，再查找 // 发货表
                    _ = factoryMes.Deletedata.FromSqlRaw(sQLa1).ToList();  // 执行SQL
                    rp.State = "0";
                    vre.State = "5"; // 维修中
                }
                else if (state == "7")
                {
                    d.State = "0";
                    vre.State = "6"; // 维修完成
                }
            }
            else
            {
                this.response.SetFailed();
            }

            context.SaveChanges();
            return this.response;
        }

        /// <summary>
        /// 核对超期统计 .
        /// </summary>
        /// <returns> .</returns>
        [Route("/api/v1/reportForms/Verificationprompt")]
        [HttpGet]
        public ResponseModel Statisticsx()
        {
            AuthContextUser currentUser = AuthContextService.CurrentUser;
            using var context = new FactoryMesContext();
            float[] str = { 0, 0, 0, 0 };

            var strsz = context.MainsortRecord.Where(x => x.State == "2" && x.Product_Category == "生产二部");
            var strqd = context.MainsortRecord.Where(x => x.State == "2" && x.Product_Category == "生产三部");
            var strdj = context.MainsortRecord.Where(x => x.State == "2" && x.Product_Category == "生产四部");
            var x = context.MainsortRecord.Where(x => x.State == "2");

            str[0] = strsz.ToList().Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days >= 2).Count();
            str[1] = strqd.ToList().Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days >= 2).Count();
            str[2] = strdj.ToList().Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days >= 2).Count();
            str[3] = x.ToList().Where(x => x.State == "2" && x.Contact_Information == "不明").Count();

            this.response.SetData(str);
            return this.response;
        }
    }
}
